import React, { useState, useEffect } from 'react';
import { X, Plus, Book } from 'lucide-react';
import { MistakeNotebook } from '../../types';
import { getMistakeNotebooks, createMistakeNotebook } from '../services/storageService';

interface AddToMistakeModalProps {
  isOpen: boolean;
  onClose: () => void;
  onAdd: (notebookId: string) => void;
}

export const AddToMistakeModal: React.FC<AddToMistakeModalProps> = ({
  isOpen,
  onClose,
  onAdd,
}) => {
  const [activeTab, setActiveTab] = useState<'existing' | 'new'>('existing');
  const [notebooks, setNotebooks] = useState<MistakeNotebook[]>([]);
  const [selectedNotebookId, setSelectedNotebookId] = useState<string>('');
  const [newNotebookName, setNewNotebookName] = useState('');

  useEffect(() => {
    if (isOpen) {
      setNotebooks(getMistakeNotebooks());
      setActiveTab('existing');
      setNewNotebookName('');
      setSelectedNotebookId('');
    }
  }, [isOpen]);

  const handleCreateNew = () => {
    if (!newNotebookName.trim()) return;
    const newNotebook = createMistakeNotebook(newNotebookName);
    onAdd(newNotebook.id);
    onClose();
  };

  const handleAddToExisting = () => {
    if (!selectedNotebookId) return;
    onAdd(selectedNotebookId);
    onClose();
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4 animate-in fade-in duration-200">
      <div className="bg-white rounded-2xl shadow-xl w-full max-w-md overflow-hidden animate-in zoom-in-95 duration-200">
        <div className="flex items-center justify-between p-4 border-b border-slate-100">
          <h3 className="font-bold text-lg text-slate-800">添加到题集</h3>
          <button
            onClick={onClose}
            className="p-1 rounded-full hover:bg-slate-100 text-slate-400 hover:text-slate-600 transition-colors"
          >
            <X size={20} />
          </button>
        </div>

        <div className="p-4">
          <div className="flex p-1 bg-slate-100 rounded-lg mb-6">
            <button
              onClick={() => setActiveTab('existing')}
              className={`flex-1 py-2 text-sm font-medium rounded-md transition-all ${
                activeTab === 'existing'
                  ? 'bg-white text-primary shadow-sm'
                  : 'text-slate-500 hover:text-slate-700'
              }`}
            >
              添加到现有
            </button>
            <button
              onClick={() => setActiveTab('new')}
              className={`flex-1 py-2 text-sm font-medium rounded-md transition-all ${
                activeTab === 'new'
                  ? 'bg-white text-primary shadow-sm'
                  : 'text-slate-500 hover:text-slate-700'
              }`}
            >
              新建题集
            </button>
          </div>

          {activeTab === 'existing' ? (
            <div className="space-y-4">
              {notebooks.length === 0 ? (
                <div className="text-center py-8 text-slate-400">
                  <Book className="w-12 h-12 mx-auto mb-2 opacity-20" />
                  <p>暂无题集，请先新建</p>
                </div>
              ) : (
                <div className="space-y-2 max-h-60 overflow-y-auto">
                  {notebooks.map((notebook) => (
                    <div
                      key={notebook.id}
                      onClick={() => setSelectedNotebookId(notebook.id)}
                      className={`p-3 rounded-xl border cursor-pointer transition-all flex items-center justify-between ${
                        selectedNotebookId === notebook.id
                          ? 'border-primary bg-indigo-50'
                          : 'border-slate-200 hover:border-primary/50 hover:bg-slate-50'
                      }`}
                    >
                      <span className={`font-medium ${selectedNotebookId === notebook.id ? 'text-primary' : 'text-slate-700'}`}>
                        {notebook.name}
                      </span>
                      <span className="text-xs text-slate-400">
                        {notebook.questions.length} 题
                      </span>
                    </div>
                  ))}
                </div>
              )}
              <button
                disabled={!selectedNotebookId}
                onClick={handleAddToExisting}
                className="w-full bg-primary hover:bg-indigo-700 disabled:opacity-50 disabled:hover:bg-primary text-white py-2.5 rounded-xl font-bold transition-all shadow-lg shadow-primary/20 mt-4"
              >
                确定添加
              </button>
            </div>
          ) : (
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">
                  题集名称
                </label>
                <input
                  type="text"
                  value={newNotebookName}
                  onChange={(e) => setNewNotebookName(e.target.value)}
                  placeholder="例如：数学错题、英语易错点..."
                  className="w-full px-4 py-2 rounded-xl border border-slate-200 focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none transition-all"
                  autoFocus
                />
              </div>
              <button
                disabled={!newNotebookName.trim()}
                onClick={handleCreateNew}
                className="w-full bg-primary hover:bg-indigo-700 disabled:opacity-50 disabled:hover:bg-primary text-white py-2.5 rounded-xl font-bold transition-all shadow-lg shadow-primary/20 flex items-center justify-center gap-2"
              >
                <Plus size={18} />
                创建并添加
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};